#!/usr/bin/env python3
"""
Ensure one blank line before and after each Markdown table in a file.
Backs up original file to .bak
Usage: python3 scripts/fix_md_tables.py path/to/file.md
"""
import sys, re

if len(sys.argv) < 2:
    print("usage: fix_md_tables.py file.md")
    sys.exit(2)

path = sys.argv[1]
with open(path, 'r', encoding='utf-8') as f:
    lines = f.readlines()

out = []
i = 0
changed = False
while i < len(lines):
    # detect table header: a line starting with '|' and next line is a separator like '|---|---'
    if i+1 < len(lines) and re.match(r'^\s*\|.*\|.*$', lines[i]) and re.match(r'^\s*\|[\s\-:|]+\|?\s*$', lines[i+1]):
        # ensure previous line is blank (unless at file start)
        if len(out) > 0 and out[-1].strip() != '':
            out.append('\n')
            changed = True
        # append header and separator and following table rows
        out.append(lines[i])
        out.append(lines[i+1])
        i += 2
        # table rows
        while i < len(lines) and re.match(r'^\s*\|', lines[i]):
            out.append(lines[i])
            i += 1
        # ensure following line is blank (unless EOF)
        if i < len(lines) and (out and (out[-1].strip() != '')):
            # if next original line isn't blank, insert blank line
            if lines[i].strip() != '':
                out.append('\n')
                changed = True
        continue
    else:
        out.append(lines[i])
        i += 1

if changed:
    bak = path + '.bak'
    with open(bak, 'w', encoding='utf-8') as f:
        f.writelines(lines)
    with open(path, 'w', encoding='utf-8') as f:
        f.writelines(out)
    print(f"Modified {path}; backup at {bak}")
else:
    print(f"No changes needed for {path}")
